package com.test.itdragon.tcp;

import java.io.*;
import java.net.Socket;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class Client {
    public static void main(String[] args) {
        try {
            Socket socket = new Socket("127.0.0.1", 12345);
            System.out.println("Connected to server");

            // 异步发送消息
            ExecutorService executorService = Executors.newSingleThreadExecutor();
            Future<Void> sendFuture = executorService.submit(() -> {
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                String message = "Hello from client";
                writer.write(message);
                writer.newLine();
                writer.flush();
                System.out.println("Sent message to server: " + message);
                return null;
            });

            // 异步接收响应
            Future<String> receiveFuture = executorService.submit(() -> {
                BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                String response = reader.readLine();
                System.out.println("Received response from server: " + response);
                return response;
            });

            // 等待发送和接收完成
            sendFuture.get();
            String response = receiveFuture.get();

            // 关闭连接
            socket.close();
            executorService.shutdown();
            System.out.println("Connection closed");
        } catch (IOException | InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
}